Skip to content

Pack Rgba32 with a native conversion and one byte shuffle - #3288

Open
sebastienros wants to merge 2 commits into
SixLabors:mainfrom
sebastienros:perf/rgba32-pack-native
Open

sebastienros wants to merge 2 commits into
SixLabors:mainfrom
sebastienros:perf/rgba32-pack-native

Conversation

@sebastienros

Copy link
Copy Markdown

Prerequisites

  • I have written a descriptive pull-request title
  • I have verified that there are no overlapping pull-requests open
  • I have verified that I am following the existing coding patterns and practice as demonstrated in the repository. These follow strict Stylecop rules 👮.
  • I have provided test coverage for my change (where applicable)

Description

The per-pixel conversions Rgba32.FromUnassociatedScaledVector4 (also FromScaledVector4 and FromVector4) and Rgba32.FromAssociatedScaledVector4 end in Rgba32.Pack. Pack clamps the scaled vector to [0, 255] and then converted it with Vector128.ConvertToInt32 (the saturating conversion, which needs extra instructions on x64 for out-of-range lanes) and four GetElement reads. After the clamp, every lane is finite and in [0, 255] (NaN maps to 0), so Vector128.ConvertToInt32Native gives the same integers, and one shuffle of the low byte of each lane gives the same pixel.

The investigation, the prototype and the benchmark code are in the collapsed section at the end.

Change (src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs, Pack): when Vector128 is hardware accelerated, ConvertToInt32Native, then Vector128.Shuffle with the constant indices 0, 4, 8, 12 (the other indices are out of range and give 0), ToScalar() of the uint, reinterpreted as Rgba32 (its field order is R, G, B, A). Without acceleration, Pack keeps the previous conversion and four GetElement reads: the software shuffle is slower there (9% to 18% in a Stopwatch loop with DOTNET_EnableHWIntrinsic=0). The scale, the half, and the clamp are unchanged.

Test (tests/ImageSharp.Tests/PixelFormats/Rgba32Tests.cs): Rgba32_FromVector4_RoundsClampsAndMapsNaNToZero converts 20,000 vectors (half of the components NaN, infinities, signed zeros, ±1e30, epsilon, and values next to the rounding midpoints and to 1) and compares each byte with the rule of Pack: scale by 255, add one half, clamp to [0, 255] with NaN as 0, truncate. It runs through FeatureTestRunner with all intrinsics and with intrinsics disabled, so both paths are checked. With the clamp replaced by Vector4.Max(vector, Vector4.Zero) (a temporary change), the test fails; with a wrong element index in the fallback (a temporary change), it fails too.

Test run (macOS 15.8.3 arm64, .NET 10, with the PNG test inputs from Git LFS): dotnet test of tests/ImageSharp.Tests with the filter Rgba32|PixelOperations|PixelBlender|PorterDuff|SimdUtils, in Release and in Debug: 44,644 passed, 12 failed, 1 skipped. main (c6d486d) gives 44,643 passed and the same 12 failures in Release; the extra test is the new one. The 12 failures are PorterDuffOutputIsCorrect, whose reference images (Git LFS objects) were not fetched for this run.

Measured (BenchmarkDotNet 0.15.8, .NET 10.0.15, Intel Xeon 2.30 GHz with AVX-512, shared cloud container; 5 warmup and 15 measured iterations of 100 ms; mean ± half of the 99.9% interval; both runs in one session). 4,096 random vectors converted in a loop (per pixel) or with one bulk call, the released package against this branch (Release build of src/ImageSharp, referenced as an assembly by the same benchmark project; measured before the fallback change, which does not change the accelerated path):

Method Released 5.0.0-alpha.0.38 This branch Change
FromUnassociatedScaledVector4, per pixel 10.879 ± 0.136 µs 5.548 ± 0.527 µs −49%
FromAssociatedScaledVector4, per pixel 26.179 ± 0.445 µs 17.242 ± 0.270 µs −34%
FromUnassociatedScaledVector4Destructive, bulk (unchanged code) 1.312 ± 0.032 µs 1.347 ± 0.024 µs —
FromAssociatedScaledVector4Destructive, bulk (unchanged code) 8.962 ± 0.116 µs 8.684 ± 0.260 µs —

The standalone prototype of the investigation (with Ssse3.Shuffle instead of Vector128.Shuffle) took 4.36 ± 0.17 µs and 15.65 ± 0.23 µs in the same run, a little faster than this branch; the portable Vector128.Shuffle was kept so that ARM64 is covered by the same code. The equality check of the benchmark project (2,000,000 vectors, a quarter of them NaN, infinities, signed zeros, out-of-range and tiny values) gives 0 differences between this branch and the prototype, which gives 0 against the released package.

To measure this branch with the benchmark at the end, replace the SixLabors.ImageSharp package reference with <Reference Include="SixLabors.ImageSharp" HintPath="<Release build of src/ImageSharp>/SixLabors.ImageSharp.dll" /> and remove the Fonts and PolygonClipper package references.

The same saturating conversion and four GetElement reads are in the Pack of Abgr32, Abgr32P, Argb32, Argb32P, Bgra32, Bgra32P, L8, and La16; they are not changed here.

Not verified: AVX2-only machines, and the tests on ARM64 (the ARM64 timing is below); the real-workload gain (a profile of the SVG work in ImageSharp.Drawing puts Pack at 7.37% of the samples of a per-pixel caller).

Measured on ARM64 (local, BenchmarkDotNet ShortRun)

BenchmarkDotNet 0.15.8, Job.ShortRun (3 warmup and 3 measured iterations, 1 launch), .NET 10.0.15 (Arm64 RyuJIT), Apple M4 Pro (14 cores, 48 GB; 128-bit AdvSIMD, no 256- or 512-bit vectors), macOS 15.8.3; mean ± half of the 99.9% interval; two rounds, main then this branch, one benchmark process at a time. Both sides are Release builds of src/ImageSharp from source, referenced as assemblies by the PerPixelPack benchmark at the end (library methods only; the prototype uses x86 intrinsics): main at c6d486d, this branch at 4abf05c. "Ratio" is the faster branch round over the faster main round. A round whose Error is larger than about half of its mean was disturbed (the M4 Pro mixes performance and efficiency cores, and 3 iterations give a wide interval); read those cells with care.

Method (4,096 vectors) main, round 1 / 2 This branch, round 1 / 2 Ratio Allocated
FromUnassociatedScaledVector4, per pixel 3.005 ± 0.188 / 3.036 ± 0.122 μs 2.312 ± 0.240 / 3.379 ± 2.771 μs 0.77 0 → 0
FromAssociatedScaledVector4, per pixel 7.763 ± 0.199 / 7.941 ± 0.092 μs 6.681 ± 1.042 / 10.12 ± 8.428 μs 0.86 0 → 0
FromUnassociatedScaledVector4Destructive, bulk (unchanged code) 2.202 ± 0.253 / 2.268 ± 0.267 μs 2.199 ± 0.056 / 3.204 ± 6.524 μs 1.00 0 → 0
FromAssociatedScaledVector4Destructive, bulk (unchanged code) 7.366 ± 0.131 / 8.326 ± 18.90 μs 7.393 ± 1.179 / 7.661 ± 3.303 μs 1.00 0 → 0

On ARM64 the portable Vector128.Shuffle path makes the per-pixel conversions 23% (unassociated) and 14% (associated) faster; the bulk methods, which do not call Pack, are unchanged (1.00). The second branch round of the table was disturbed (its Errors are as large as its means), so a check ran with 3 launches per round (Job.ShortRun.WithLaunchCount(3), two rounds, 6 launches per side): unassociated per pixel 3.03 to 3.13 µs on main against 2.33 to 2.38 µs on this branch in every launch (0.77), associated per pixel 7.92 to 7.96 against 6.86 to 7.09 µs (0.87), and the bulk methods 1.00 and 1.01 (fastest launches). This covers the timing on ARM64 only: the tests were not run on this machine.

Investigation and benchmark code

Investigation

Source: PixelFormats/PixelImplementations/Rgba32.cs, Pack(Vector4):

vector *= MaxBytes;
vector += Half;
vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes);
Vector128<byte> result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte();
return new Rgba32(result.GetElement(0), result.GetElement(4), result.GetElement(8), result.GetElement(12));

FromAssociatedScaledVector4 calls PixelOperations<Rgba32>.FromAssociatedScaledVector4, which applies PixelOperations.UnassociateOperator.Apply (an alpha clamp, a division, ClampToPixelRange) and then FromUnassociatedScaledVector4, that is Pack.

Measurement in the SVG work in ImageSharp.Drawing (SVG_DESIGN.md section 20.1, "Texture brush", perf, FilterShadows at 1000 px, one thread, ImageSharp 5.0.0-alpha.0.38): the per-pixel TPixel.FromAssociatedScaledVector4 inside the generic texture brush showed UnassociateOperator.Apply and Rgba32.Pack as two calls that were not inlined, 8.75% and 7.37% of the samples. In a small loop (the benchmark below) the JIT inlines both, so the "not inlined" part depends on the caller; the cost of Pack itself shows in both.

Measured in isolation (below): per million pixels, the library per-pixel unassociated form takes 2.7 to 3.8 ms (two runs), the associated form 6.3 to 6.4 ms, the bulk forms 0.33 ms and 1.8 to 2.1 ms; the prototype per-pixel forms 1.05 ms and 3.8 to 3.9 ms.

Benchmark to validate

Machine: Intel Xeon 2.30 GHz, 4 cores (shared cloud container, AVX-512: x86-64-v4), Ubuntu 24.04, .NET 10.0.15 (SDK 10.0.404), BenchmarkDotNet 0.15.8. Job: 5 warmup and 15 measured iterations of 100 ms, 1 launch. Error is half of the 99.9% confidence interval.

4,096 random vectors (alpha in [0, 1]; the associated input is the straight input times its alpha), converted in a loop with the library method, with the prototype, and with the bulk method:

Method Mean Error StdDev Allocated
'unassociated, per pixel, library' 11.004 μs 0.1593 μs 0.1330 μs -
'unassociated, per pixel, prototype' 4.299 μs 0.0976 μs 0.0815 μs -
'unassociated, bulk, library' 1.352 μs 0.0316 μs 0.0263 μs -
'associated, per pixel, library' 25.737 μs 0.6173 μs 0.5155 μs -
'associated, per pixel, prototype' 15.678 μs 0.3013 μs 0.2819 μs -
'associated, bulk, library' 8.666 μs 0.3428 μs 0.3039 μs -

A first run gave 15.66 ± 0.10 µs for the library unassociated loop (prototype 4.34 µs), 26.35 µs for the associated loop (prototype 16.07 µs), and the same bulk times; the library unassociated loop is the one cell that moved between the runs.

The equality check converts 2,000,000 vectors with both the library and the prototype, for both the associated and the unassociated method: a quarter of them are made of NaN, infinities, signed zeros, out-of-range and tiny values, the others random associated colours (some 1.2 times out of range). Result: 0 differences.

What result means the fix works: the patched Rgba32.FromUnassociatedScaledVector4 and FromAssociatedScaledVector4 take the prototype times (within the error), and the equality check passes against the patched library.

How to build and run:

  1. Put the files below in one directory (Bench.csproj, NuGet.config, Program.cs, and the .cs files).
  2. dotnet build -c Debug (the project sets <Optimize>true</Optimize>; see the note on the license check).
  3. Equality check: dotnet bin/Debug/net10.0/Bench.dll check.
  4. Benchmark: dotnet bin/Debug/net10.0/Bench.dll --filter '*.PerPixelPack.*'.

Note on the build: the Six Labors packages run a license check in every build whose configuration does not start with Debug; without a license key, a Release build fails. The project therefore builds the Debug configuration with <Optimize>true</Optimize>, and the job uses WithCustomBuildConfiguration("Debug"), so BenchmarkDotNet builds its generated project the same way and accepts it as optimized. With a license key set (SixLaborsLicenseKey), a Release build and the default job work too.

Bench.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>disable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <ImplicitUsings>enable</ImplicitUsings>
    <Optimize>true</Optimize>
    <DebugType>portable</DebugType>
    <TieredPGO>true</TieredPGO>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
    <PackageReference Include="SixLabors.ImageSharp" Version="5.0.0-alpha.0.38" />
    <PackageReference Include="SixLabors.Fonts" Version="3.2.1" />
    <PackageReference Include="SixLabors.PolygonClipper" Version="2.0.0-alpha.0.2" />
  </ItemGroup>
</Project>

NuGet.config (the prerelease packages are on the Six Labors feed):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
    <add key="feedz-sixlabors" value="https://f.feedz.io/sixlabors/sixlabors/nuget/index.json" />
  </packageSources>
</configuration>

Program.cs:

using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using Perfolizer.Horology;
using Bench;

if (args.Length > 0 && args[0] == "check")
{
    return PackChecks.Run();
}

// The Six Labors packages check for a license in builds whose configuration does not start with "Debug".
// Bench.csproj sets Optimize=true, so the Debug build is optimized; BenchmarkDotNet builds with that configuration.
IConfig config = DefaultConfig.Instance
    .AddJob(Job.Default
        .WithCustomBuildConfiguration("Debug")
        .WithWarmupCount(5)
        .WithIterationCount(15)
        .WithIterationTime(TimeInterval.FromMilliseconds(100))
        .WithLaunchCount(1));

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, config);
return 0;

ProtoPack.cs:

using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using SixLabors.ImageSharp.PixelFormats;

namespace Bench;

/// <summary>
/// Prototype of the per-pixel Rgba32.FromUnassociatedScaledVector4 and Rgba32.FromAssociatedScaledVector4
/// (SixLabors.ImageSharp 5.0.0-alpha.0.38). The library packs with Vector128.ConvertToInt32 (saturating conversion)
/// and four GetElement calls. The values are already clamped to [0, 255] at that point, so the prototype uses
/// ConvertToInt32Native (cvttps2dq) and one byte shuffle. The arithmetic before the conversion is unchanged.
/// </summary>
public static class ProtoPack
{
    private static readonly Vector128<byte> PackShuffle = Vector128.Create((byte)0, 4, 8, 12, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80);

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static Rgba32 FromUnassociatedScaledVector4(Vector4 source) => Pack(source.AsVector128());

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static Rgba32 FromAssociatedScaledVector4(Vector4 source)
    {
        Vector128<float> s = source.AsVector128();
        Vector128<float> alphaMask = Vector128.Create(0, 0, 0, -1).AsSingle();

        // UnassociateOperator.Apply: alpha clamped to [0, float.MaxValue], RGB divided by it (by 1 for alpha 0).
        Vector128<float> alpha = Sse.Shuffle(s, s, 0b_11_11_11_11);
        alpha = Clamp(alpha, Vector128<float>.Zero, Vector128.Create(float.MaxValue));
        s = Vector128.ConditionalSelect(alphaMask, alpha, s);
        Vector128<float> maximumMask = Vector128.Equals(alpha, Vector128<float>.Zero) | alphaMask;
        s /= Vector128.ConditionalSelect(maximumMask, Vector128.Create(1F), alpha);

        // ClampToPixelRange.
        s = Clamp(s, Vector128.Create(-65504F, -65504F, -65504F, 0F), Vector128.Create(65504F, 65504F, 65504F, 1F));
        return Pack(s);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static Rgba32 Pack(Vector128<float> v)
    {
        // Rgba32.Pack: scale, add one half, clamp to [0, 255] (NaN to 0), truncate.
        v = (v * Vector128.Create(255F)) + Vector128.Create(.5F);
        v = Clamp(v, Vector128<float>.Zero, Vector128.Create(255F));

        // The clamped value is finite and in [0, 255]: the native truncation equals the saturating one.
        Vector128<byte> bytes = Ssse3.Shuffle(Vector128.ConvertToInt32Native(v).AsByte(), PackShuffle);
        uint packed = bytes.AsUInt32().ToScalar();
        return Unsafe.As<uint, Rgba32>(ref packed);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static Vector128<float> Clamp(Vector128<float> value, Vector128<float> min, Vector128<float> max)
    {
        Vector128<float> lower = Vector128.ConditionalSelect(Vector128.GreaterThanOrEqual(value, min), value, min);
        return Vector128.ConditionalSelect(Vector128.GreaterThan(value, max), max, lower);
    }
}

PackChecks.cs:

using System.Numerics;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;

namespace Bench;

/// <summary>Compares the per-pixel pack prototype with the library, bit for bit, on random and edge inputs.</summary>
public static class PackChecks
{
    public static int Run()
    {
        int failures = CheckPack();
        Console.WriteLine(failures == 0 ? "ALL CHECKS PASSED" : $"FAILURES: {failures}");
        return failures;
    }

    public static int CheckPack()
    {
        Random random = new(7);
        int bad = 0;
        float[] specials = [float.NaN, float.PositiveInfinity, float.NegativeInfinity, -0F, 0F, 1F, 2F, -1F, 1e-30F, 1e30F, 0.5F / 255, 1.5F / 255];
        const int count = 2_000_000;
        for (int n = 0; n < count; n++)
        {
            Vector4 v;
            if (n % 4 == 0)
            {
                v = new Vector4(specials[random.Next(specials.Length)], specials[random.Next(specials.Length)], specials[random.Next(specials.Length)], specials[random.Next(specials.Length)]);
            }
            else
            {
                float a = n % 4 == 1 ? (float)random.NextDouble() : random.Next(256) / 255F;
                v = new Vector4((float)random.NextDouble() * a, (float)random.NextDouble() * a, (float)random.NextDouble() * a, a);
                if (n % 16 == 3)
                {
                    v *= 1.2F;
                }
            }

            Rgba32 l1 = Rgba32.FromAssociatedScaledVector4(v);
            Rgba32 p1 = ProtoPack.FromAssociatedScaledVector4(v);
            Rgba32 l2 = Rgba32.FromUnassociatedScaledVector4(v);
            Rgba32 p2 = ProtoPack.FromUnassociatedScaledVector4(v);
            if (l1 != p1 || l2 != p2)
            {
                if (bad < 5)
                {
                    Console.WriteLine($"  pack differs for {v}: {l1}/{p1} {l2}/{p2}");
                }

                bad++;
            }
        }

        Console.WriteLine($"per-pixel pack: {count} vectors (a quarter with NaN, infinities, signed zeros, out-of-range values), {bad} differ");
        return bad;
    }
}

PackBenchmarks.cs:

using System.Numerics;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;

namespace Bench;

/// <summary>Candidate 3: per-pixel and bulk conversion of 4096 vectors to Rgba32.</summary>
[MemoryDiagnoser]
public class PerPixelPack
{
    private const int Count = 4096;
    private Vector4[] associated;
    private Vector4[] unassociated;
    private Rgba32[] output;

    [GlobalSetup]
    public void Setup()
    {
        Random random = new(3);
        this.associated = new Vector4[Count];
        this.unassociated = new Vector4[Count];
        for (int i = 0; i < Count; i++)
        {
            float a = (float)random.NextDouble();
            Vector4 straight = new((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), a);
            this.unassociated[i] = straight;
            this.associated[i] = new Vector4(straight.X * a, straight.Y * a, straight.Z * a, a);
        }

        this.output = new Rgba32[Count];
    }

    [Benchmark(Description = "unassociated, per pixel, library")]
    public void UnassociatedLibrary()
    {
        Vector4[] source = this.unassociated;
        Rgba32[] destination = this.output;
        for (int i = 0; i < source.Length; i++)
        {
            destination[i] = Rgba32.FromUnassociatedScaledVector4(source[i]);
        }
    }

    [Benchmark(Description = "unassociated, per pixel, prototype")]
    public void UnassociatedPrototype()
    {
        Vector4[] source = this.unassociated;
        Rgba32[] destination = this.output;
        for (int i = 0; i < source.Length; i++)
        {
            destination[i] = ProtoPack.FromUnassociatedScaledVector4(source[i]);
        }
    }

    [Benchmark(Description = "unassociated, bulk, library")]
    public void UnassociatedBulk()
        => PixelOperations<Rgba32>.Instance.FromUnassociatedScaledVector4Destructive(Configuration.Default, this.unassociated, this.output);

    [Benchmark(Description = "associated, per pixel, library")]
    public void AssociatedLibrary()
    {
        Vector4[] source = this.associated;
        Rgba32[] destination = this.output;
        for (int i = 0; i < source.Length; i++)
        {
            destination[i] = Rgba32.FromAssociatedScaledVector4(source[i]);
        }
    }

    [Benchmark(Description = "associated, per pixel, prototype")]
    public void AssociatedPrototype()
    {
        Vector4[] source = this.associated;
        Rgba32[] destination = this.output;
        for (int i = 0; i < source.Length; i++)
        {
            destination[i] = ProtoPack.FromAssociatedScaledVector4(source[i]);
        }
    }

    // Destructive by contract; for Rgba32 the bulk associated path reads the source only.
    [Benchmark(Description = "associated, bulk, library")]
    public void AssociatedBulk()
        => PixelOperations<Rgba32>.Instance.FromAssociatedScaledVector4Destructive(Configuration.Default, this.associated, this.output);
}

Rgba32.Pack clamps the scaled vector to [0, 255] before the conversion, so the
saturating Vector128.ConvertToInt32 and the four GetElement reads can be replaced
by ConvertToInt32Native and one shuffle of the low bytes with the same result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01871HTtWub3CsCnBstKx55h
Without hardware acceleration Vector128.Shuffle runs a software loop that
is slower than four element reads (9% to 18% in a Stopwatch loop with
DOTNET_EnableHWIntrinsic=0). Pack now uses the shuffle only when
Vector128 is accelerated, and the Pack test runs with and without
intrinsics so that both paths are checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01871HTtWub3CsCnBstKx55h
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants